#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include "Common.hpp"

static const std::string default_ip = "0.0.0.0";

class InitAddr
{
public:
    InitAddr() {}

    InitAddr(struct sockaddr_in addr)
        : _addr(addr)
    {
        SetAddr(addr);
    }

    InitAddr(uint16_t port, const std::string &ip = default_ip)
        : _port(port), _ip(ip)
    {
        std::cout << "1";
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port);
        _addr.sin_addr.s_addr = INADDR_ANY;
    }

    uint16_t port()
    {
        return _port;
    }

    struct sockaddr_in &NetAddr()
    {
        return _addr;
    }

    struct sockaddr *NetAddrPtr()
    {
        return CONV(_addr); // 定义在Common.hpp中的宏
    }

    socklen_t NetAddrLen()
    {
        return sizeof(_addr);
    }

    bool operator==(InitAddr &peer)
    {
        return _port == peer.port() && _ip == peer.ip();
    }

    void SetAddr(struct sockaddr_in &addr)
    {
        _addr = addr;
        std::cout << "2";
        _port = ntohs(_addr.sin_port);
        char ipbuffer[64];
        inet_ntop(AF_INET, &_addr.sin_family, ipbuffer, sizeof(ipbuffer));
        _ip = ipbuffer;
    }

    std::string StringAddr()
    {
        std::string str = _ip + "  " + std::to_string(_port);
        return str;
    }

    std::string ip()
    {
        return _ip;
    }

private:
    struct sockaddr_in _addr;
    uint16_t _port;
    std::string _ip;
};